<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getBannerListApi, createBannerApi, updateBannerApi, deleteBannerApi, batchDeleteBannerApi, updateBannerStatusApi } from "@/api/banner-manage"
import { type BannerVo, type CreateBannerRequest, type UpdateBannerRequest } from "@/api/banner-manage/types/banner"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"
import ImageUpload from "@/components/ImageUpload/index.vue"

defineOptions({
  // 命名当前组件
  name: "BannerManage"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 新增/修改轮播图
const DEFAULT_FORM_DATA: CreateBannerRequest = {
  type: 1,
  image: "",
  link: "",
  title: "",
  sort: 0,
  status: 1
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateBannerRequest>(cloneDeep(DEFAULT_FORM_DATA))
const isUpdate = ref<boolean>(false)

const formRules: FormRules<CreateBannerRequest> = {
  type: [{ required: true, trigger: "change", message: "请选择轮播图类型" }],
  image: [{ required: true, trigger: "blur", message: "请输入图片地址" }],
  sort: [{ required: true, trigger: "blur", message: "请输入排序值" }],
  status: [{ required: true, trigger: "change", message: "请选择状态" }]
}

const handleCreate = () => {
  dialogVisible.value = true
  isUpdate.value = false
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const handleUpdate = (row: BannerVo) => {
  dialogVisible.value = true
  isUpdate.value = true
  formData.value = {
    type: row.type,
    image: row.image,
    link: row.link || "",
    title: row.title || "",
    sort: row.sort,
    status: row.status
  }
  ;(formData.value as UpdateBannerRequest).id = row.id
}

const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    
    const api = isUpdate.value ? updateBannerApi : createBannerApi
    api(formData.value as any)
      .then(() => {
        ElMessage.success(isUpdate.value ? "修改成功" : "创建成功")
        dialogVisible.value = false
        getBannerData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

// 删除轮播图
const handleDelete = (row: BannerVo) => {
  ElMessageBox.confirm(`正在删除轮播图：${row.title || '未命名'}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteBannerApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getBannerData()
    })
  })
}

// 批量删除
const multipleTableRef = ref()
const multipleSelection = ref<BannerVo[]>([])

const handleSelectionChange = (val: BannerVo[]) => {
  multipleSelection.value = val
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的轮播图")
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 个轮播图？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id)
    batchDeleteBannerApi(ids).then(() => {
      ElMessage.success("批量删除成功")
      getBannerData()
    })
  })
}

// 更新状态
const handleStatusChange = (row: BannerVo, status: number) => {
  const statusText = status === 1 ? "启用" : "禁用"
  ElMessageBox.confirm(`确认${statusText}该轮播图？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    updateBannerStatusApi(row.id, status).then(() => {
      ElMessage.success(`${statusText}成功`)
      getBannerData()
    })
  })
}

// 查询轮播图数据
const bannerData = ref<BannerVo[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  title: "",
  type: "",
  status: ""
})

const getBannerData = () => {
  loading.value = true
  getBannerListApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    title: searchData.title || undefined,
    type: searchData.type ? Number(searchData.type) : undefined,
    status: searchData.status ? Number(searchData.status) : undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      bannerData.value = data.list
    })
    .catch(() => {
      bannerData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getBannerData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// 格式化显示
const formatBannerType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "商家推广",
    2: "优惠券活动"
  }
  return typeMap[type] || "未知类型"
}

const formatStatus = (status: number) => {
  return status === 1 ? "启用" : "禁用"
}

// 图片上传回调
const handleUploadSuccess = (result: any) => {
  console.log('图片上传成功:', result)
}

const handleUploadError = (error: any) => {
  console.error('图片上传失败:', error)
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getBannerData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="title" label="轮播图标题">
          <el-input v-model="searchData.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="type" label="轮播图类型">
          <el-select v-model="searchData.type" placeholder="请选择" clearable style="width: 140px;">
            <el-option label="商家推广" value="1" />
            <el-option label="优惠券活动" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleCreate">新增轮播图</el-button>
          <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getBannerData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table ref="multipleTableRef" :data="bannerData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="title" label="标题" align="center" min-width="120">
            <template #default="scope">
              {{ scope.row.title || '未设置' }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" align="center" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.type === 1 ? 'success' : scope.row.type === 2 ? 'warning' : 'info'" effect="plain" disable-transitions>
                {{ formatBannerType(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="image" label="图片" align="center" width="120">
            <template #default="scope">
              <el-image
                style="width: 80px; height: 40px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
                preview-teleported
              />
            </template>
          </el-table-column>
          <el-table-column prop="link" label="链接地址" align="center" min-width="200">
            <template #default="scope">
              <span v-if="scope.row.link" class="link-text">{{ scope.row.link }}</span>
              <span v-else class="text-gray">未设置</span>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" align="center" width="80" />
          <el-table-column prop="status" label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="plain" disable-transitions>
                {{ formatStatus(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <el-button 
                type="primary" 
                text 
                bg 
                size="small" 
                @click="handleUpdate(scope.row)"
              >
                修改
              </el-button>
              <el-button 
                v-if="scope.row.status === 1"
                type="warning" 
                text 
                bg 
                size="small" 
                @click="handleStatusChange(scope.row, 0)"
              >
                禁用
              </el-button>
              <el-button 
                v-else
                type="success" 
                text 
                bg 
                size="small" 
                @click="handleStatusChange(scope.row, 1)"
              >
                启用
              </el-button>
              <el-button 
                type="danger" 
                text 
                bg 
                size="small" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isUpdate ? '修改轮播图' : '新增轮播图'"
      @closed="resetForm"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="type" label="轮播图类型">
              <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="商家推广" :value="1" />
                <el-option label="优惠券活动" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status" label="状态">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="title" label="标题">
          <el-input v-model="formData.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        <el-form-item prop="image" label="轮播图片">
          <ImageUpload 
            v-model="formData.image" 
            :multiple="false"
            folder="banner"
            @upload-success="handleUploadSuccess"
            @upload-error="handleUploadError"
          />
        </el-form-item>
        <el-form-item prop="link" label="链接地址">
          <el-input v-model="formData.link" placeholder="请输入链接地址（可选）" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="sort" label="排序">
              <el-input-number v-model="formData.sort" :min="0" style="width: 100%" placeholder="数值越大排序越靠前" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.link-text {
  color: #409eff;
  cursor: pointer;
  word-break: break-all;
}

.text-gray {
  color: #999;
}
</style>